/*
 * FOF资产策略配置图表模块
 */
require('!style!css!../css/configGraph.css');
var configGraphHtml = require('!html!../html/configGraph.html');
var common = require('./common.js');
var loading = require('./loading.js');
var page = require('./page.js');
var fund = require('./fund.js');
require('./bigJSON1.js');
var configGraphVue;
var configGraph = {
    myChart: null,
    configEChart: null,
    hasLoaded: false,
    jsonData: null,
    paramJson: null,
    nearRiskDot: {},
    init: function (paramJson) {
        configGraph.paramJson = paramJson;
        page.setPage(4);
        common.initNav(2);
        $('.step').hide();
        $('#configGraph').html(configGraphHtml).show();
        configGraph.initCallback();
        loading.start();
        common.getData({
            path: 'assetOrStrategyStart',
            callback: 'loadAssetOrStrategyStartResult',
            extra: '?calType=1&params=' + encodeURIComponent(JSON.stringify(paramJson))
        });
    },
    isCustomWeight: function () {
        return configGraph.paramJson.modelId == 4;
    },
    setTimeoutLoadResult: function () {
        setTimeout(function () {
            if (configGraph.isCustomWeight()) {
                common.getData({
                    path: 'assetOrStrategyResultCustom',
                    callback: 'loadAssetOrStrategyResultCustom',
                    extra: '?calType=1&taskId=' + window['taskId']
                });
            } else {
                common.getData({
                    path: 'assetOrStrategyResult',
                    callback: 'loadAssetOrStrategyResult',
                    extra: '?calType=1&taskId=' + window['taskId']
                });
            }
        }, 2000);
    },
    initCallback: function () {
        page.initSelectedParams(4);
        window['loadAssetOrStrategyResultShow'] = false;
        configGraph.hasLoaded = false;
        window['loadAssetOrStrategyStartResult'] = function (json) {
            var taskId = common.filterData(json, 'taskId');
            if (taskId) {
                window['taskId'] = taskId;
                configGraph.setTimeoutLoadResult();
            }
        };
        window['loadAssetOrStrategyResult'] = window['loadAssetOrStrategyResultCustom'] = function (json) {
            if (!json || !json.code || json.code == -2 || json.code == -3) {
                //计算失败 未查到任务
                alert('计算异常，错误码：' + json.code);
                return;
            }
            if (window.location.href.indexOf('testConfig=1') > -1) {
                json = big1;
            }
            if (json && json.code != 200) {
                configGraph.setTimeoutLoadResult();
                return;
            }
            if (configGraph.isCustomWeight()) {
                loading.end();
                $('#pointContent').hide();
                $('#configGraph').find('.accept button').off().on('click', function () {
                    configGraph.next();
                });
                var configModel = $('#config').find('.config-model');
                var configModelInput = configModel.find('input');
                $('#graph').html('<div class="config-model" style="width: 95%;">' + configModel.html() + '</div>');
                $('#graph').find('.config-model').find('input').each(function (i) {
                    $(this).val(configModelInput.eq(i).val()).attr('disabled', 'true');
                });
                configGraph.goECharts(json);
                return;
            }
            $('#pointContent').show();
            configGraph.jsonData = json;
            var data = common.filterData(json, 'pointList');
            if (data) {
                if (window['loadAssetOrStrategyResultShow']) {
                    return;
                } else {
                    window['loadAssetOrStrategyResultShow'] = true;
                }
            }
            var risk = configGraph.paramJson.risk;
            var nearRiskIndex = -1;
            var nearRiskData = '';
            var hasNearRisk = false;
            var bigRisk = 0;
            var bigRiskIndex = 0;
            var bigRiskData = '';
            var tempData = data;
            try {
                $.each(tempData, function (k, v) {
                    var tempV = [];
                    $.each(v, function (kk, vv) {
                        if (typeof vv == 'object') {
                            var cashArray = [];
                            var tempVV = {};
                            $.each(vv, function (kkk, vvv) {
                                if (kkk == '现金') {
                                    cashArray.push(vvv);
                                } else {
                                    tempVV[kkk] = vvv;
                                }
                            });
                            if (cashArray.length > 0) {
                                tempVV['现金'] = cashArray[0];
                            }
                            tempV.push(tempVV);
                        } else {
                            tempV.push(vv);
                        }
                    });
                    tempData[k] = tempV;
                });
                data = tempData;
            } catch (e) {
                console.log(e.message);
            }
            console.log(data);
            var pointList = data;
            $.each(pointList, function (k, v) {
                $.each(v, function (kk, vv) {
                    if (typeof vv != 'object') {
                        pointList[k][kk] = parseFloat(parseFloat(vv) * 100).toFixed(2);
                    }
                    if (kk == 0) {
                        if (pointList[k][kk] > bigRisk) {
                            bigRisk = vv;
                            bigRiskIndex = k;
                            bigRiskData = pointList[k];
                        }
                        if (!hasNearRisk) {
                            if (pointList[k][kk] >= risk) {
                                hasNearRisk = true;
                                nearRiskIndex = k;
                                nearRiskData = pointList[k];
                            }
                        }
                    }
                });
            });
            if (!hasNearRisk) {
                nearRiskIndex = bigRiskIndex;
                nearRiskData = bigRiskData;
            }
            configGraph.nearRiskDot = {
                dataIndex: nearRiskIndex,
                data: nearRiskData,
                componentType: 'series'
            };
            console.log('nearRiskIndex:', nearRiskIndex);
            console.log('nearRiskData:', nearRiskData);
            loading.end();
            console.log('pointList', pointList);
            configGraph.showGraph(pointList);
            configGraph.goECharts(json);
        };
    },
    showGraph: function (data) {
        if (configGraph.hasLoaded) {
            return false;
        }
        $('#graph').html('');
        var dom = document.getElementById('graph');
        this.myChart = echarts.init(dom);
        var myChart = this.myChart;
        var option = null;
        option = {
            title: {
                text: '收益风险图',
                left: 'center'
            },
            grid: {
                left: '3%',
                right: '15%',
                bottom: '3%',
                containLabel: true
            },
            tooltip: {
                trigger: 'axis',
                showDelay: 0,
                formatter: function (params) {
                    if (params.value.length > 1) {
                        var other = '';
                        return params.seriesName + ':<br>'
                            + '风险：' + params.value[0] + '%<br>'
                            + '收益：' + params.value[1] + '%<br>'
                            + other;
                    }
                },
                axisPointer: {
                    show: true,
                    type: 'cross',
                    lineStyle: {
                        type: 'dashed',
                        width: 1
                    }
                }
            },
            toolbox: {
                show: false,
                feature: {
                    dataZoom: {},
                    brush: {
                        type: ['rect', 'polygon', 'clear']
                    }
                }
            },
            brush: {},
            legend: {
                show: false,
                data: ['收益风险图'],
                left: 'center'
            },
            xAxis: [
                {
                    name: '风险值(%)',
                    type: 'value',
                    scale: true,
                    axisLabel: {
                        formatter: '{value}'
                    },
                    splitLine: {
                        show: false
                    }
                }
            ],
            yAxis: [
                {
                    name: '收益值(%)',
                    type: 'value',
                    scale: true,
                    axisLabel: {
                        formatter: '{value}'
                    },
                    splitLine: {
                        show: false
                    }
                }
            ],
            series: [
                {
                    name: '相关参数值',
                    type: 'scatter',
                    symbolSize: 5,
                    data: data
                }
            ]
        };

        var checkParams = function (params) {
            if (params.componentType == 'series') {
                console.log('dataIndex:' + params.dataIndex);
                if (typeof params.dataIndex != 'undefined') {
                    configGraph.highlight(params.dataIndex);
                    configGraphVue.graphList = [configGraphVue.graphAll[params.dataIndex]];
                    configGraphVue.dotSelect = true;
                    configGraphVue.dot.dataIndex = params.dataIndex;
                    configGraphVue.dot.risk = params.data[0] + '%';
                    configGraphVue.dot.profit = params.data[1] + '%';
                    configGraph.createNewLine(params.dataIndex);
                    console.log(configGraphVue.graphList);
                }
            }
        };
        if (option && typeof option === 'object') {
            configGraph.hasLoaded = true;
            myChart.setOption(option, true);
            myChart.on('click', function (params) {
                console.log('click', params);
                checkParams(params);
            });
            myChart.on('mouseout', function (params) {
                console.log('mouseout', params);
                if (params.componentType == 'series') {
                    if (typeof params.dataIndex != 'undefined') {
                        if (configGraphVue.dot.dataIndex > -1) {
                            configGraph.highlight(configGraphVue.dot.dataIndex);
                        }
                    }
                }
            });
        }
        var titleList = [];
        $.each(data[0][2], function (k, v) {
            titleList.push(k);
        });
        configGraphVue = new Vue({
            el: '#configGraph',
            data: {
                titleList: titleList,
                graphAll: data,
                graphList: [],
                dotSelect: false,
                dot: {
                    dataIndex: -1,
                    risk: '',
                    profit: ''
                }
            },
            methods: {
                selectDot: function (e) {
                    var thisObj = $(e.target);
                    thisObj.addClass('on').siblings().removeClass('on');
                    configGraph.highlight(thisObj.index());
                },
                accept: function () {
                    configGraph.next();
                }
            }
        });
        console.log('select default risk:' + configGraph.paramJson.risk);
        setTimeout(function () {
            checkParams(configGraph.nearRiskDot);
        }, 50)
    },
    next: function () {
        console.log('accept click...');
        if (!configGraph.isCustomWeight()) {
            if ($('.graph_0').size() == 0) {
                alert('请选择一行数据');
                return false;
            }
            window['configGraphDot'] = configGraphVue.dot;
        }
        fund.init();
    },
    highlight: function (index) {
        var myChart = this.myChart;
        if (myChart) {
            myChart.dispatchAction({
                type: 'downplay'
            });
            myChart.dispatchAction({
                type: 'highlight',
                dataIndex: index
            });
        }
    },
    resetData: function (data) {
        var bigJSON = {};
        var dataArray = [];
        var nameArray = [];
        $.each(data, function (k, v) {
            nameArray.push(v.assetStrategyName);
        });
        $.each(data[0].priceList, function (k, v) {
            var childArray = [];
            childArray.push(v.date);
            $.each(nameArray, function (kk, vv) {
                childArray.push(data[kk].priceList[k].price);
            });
            dataArray.push(childArray);
        });
        bigJSON.dataArray = dataArray;
        bigJSON.nameArray = nameArray;
        return bigJSON;
    },
    goECharts: function (json) {
        this.configEChart = common.createECharts({
            json: json,
            bigJSONFunction: function (jsondata) {
                return configGraph.resetData(common.filterData(jsondata, 'benchMarkPriceTrend'));
            },
            domId: 'configECharts',
            text: '指数曲线图'
        });
    },
    createNewLine: function (pointIndex) {
        try {
            pointIndex = pointIndex || 0;
            var myChart = this.configEChart;
            var option = myChart.getOption();
            var series = option.series;
            var newValues = [];
            var pointList = this.jsonData.data.pointList;
            var lineSourceLength = this.jsonData.data.benchMarkPriceTrend.length;
            var bigNumArray = [];
            $.each(series, function (k, v) {
                if (k >= lineSourceLength) {
                    return true;
                }
                var name = v.name;
                var data = v.data;
                var numArray = [];
                $.each(data, function (kk, vv) {
                    var num = parseFloat(pointList[pointIndex][2][name]) * parseFloat(vv);
                    numArray.push(num);
                });
                bigNumArray.push(numArray);
            });
            $.each(series[0].data, function (k, v) {
                $.each(bigNumArray, function (kk, vv) {
                    if (typeof newValues[k] != 'undefined') {
                        newValues[k] += parseFloat(vv[k]);
                    } else {
                        newValues[k] = parseFloat(vv[k]);
                    }
                });
            });
            $.each(newValues, function (k, v) {
                newValues[k] = parseFloat(v).toFixed(2);
            });
            if (series.length > lineSourceLength) {
                series[series.length - 1].data = newValues;
            } else {
                series.push({
                    name: 'FOF组合配置',
                    type: 'line',
                    data: newValues,
                    smooth: true,
                    lineStyle: {
                        normal: {opacity: 0.5}
                    }
                });
            }
            option.series = series;
            myChart.setOption(option);
        } catch (e) {
            alert(e.message);
        }
    }
};
for (var key in configGraph) {
    if (key) {
        exports[key] = configGraph[key];
    }
}